use std::collections::HashMap;
use std::env;
use std::fs::File;
use std::io::{BufRead, BufReader};

#[derive(Debug)]
struct WordCounter(HashMap<String, u64>);

impl WordCounter {
    fn new() -> WordCounter {
        WordCounter(HashMap::new())
    }

    fn increment(&mut self, word: &str) {
        let key = word.to_string();
        let count = self.0.entry(key).or_insert(0);
        *count += 1;
    }

    fn display(&self, count: u64) {
        let mut hash_vec: Vec<_> = self.0.iter().collect();
        hash_vec.sort_by(|a, b| a.1.cmp(b.1).then(a.0.cmp(b.0)));
        for (key, value) in hash_vec {
            if *value >= count {
                println!("{key}: {value}");
            }
        }

        // for (key, value) in self.0.iter() {
        //     if *value >= count {
        //         println!("{key}: {value}");
        //     }
        // }
    }
}

fn main() {
    let arguments = env::args().collect::<Vec<String>>();
    let filename = arguments[1].clone();
    println!("Processing File: {filename}");
    let file = File::open(filename).expect("could not open file");
    let reader = BufReader::new(file);
    let mut word_counter = WordCounter::new();

    for line in reader.lines() {
        let line = line.expect("could not read line");
        let words = line.split(" ");
        for word in words {
            if word == "" {
                continue;
            } else {
                word_counter.increment(word);
            }
        }
    }

    word_counter.display(2);
    word_counter.display(2);
}